﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// 网络辅助操作
    /// </summary>
    public static class NetHelper
    {
        /// <summary>
        /// 是否能Ping通指定主机
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool Ping(string ip)
        {
            try
            {
                Ping ping = new();
                PingOptions options = new() { DontFragment = true };
                string data = "Test Data";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 1000;
                PingReply reply = ping.Send(ip, timeout, buffer, options);
                return reply != null && reply.Status == IPStatus.Success;
            }
            catch (PingException)
            {
                return false;
            }
        }
        
        /// <summary>
        /// 网络是否畅通
        /// </summary>
        [SupportedOSPlatform("windows")]
        public static bool IsInternetConnected()
        {
            bool state = InternetGetConnectedState(out _, 0);
            return state;
        }


        #region 私有静态方法
        /// <summary>
        /// Internet连接状态
        /// </summary>
        /// <param name="connectionDescription">连接描述</param>
        /// <param name="reservedValue">保留值</param>
        /// <returns></returns>
        [DllImport("wininet.dll")]
        [SupportedOSPlatform("windows")]
        private static extern bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

        #endregion

    }
}
